<?php

	/**
	 * @see Zend_Db_Table_Abstract
	 */
	require_once 'Zend/Db/Table/Abstract.php';
	
	/**
	 * @see Bike_Language
	 */
	require_once 'Bike/Language.php';
	
	
	class Bike_Db_Table extends Bike_Db_Table_Abstract
	{		const COLUMN_NAME_GLUE = '_';
		
		const LOCALIZATION = 'localization';
		const IDENTITY = 'identity';

		protected $_localization = False;
		protected $_localizedFields;
		protected $_undefinedLocalizedFields;
		protected $_localizedFieldsPrefixes;
		
		static public function getLanguage()
		{
			return Bike_Language::getInstance()->getLanguage();
		}
		
		static public function getLocales()
		{
			return Bike_Language::getInstance()->getLocaleArray();
		}
		
		static public function getLanguages()
		{
			return array_keys(self::getLocales());
		}
		
		static public function getColumnNameGlue()
		{
			return self::COLUMN_NAME_GLUE;
		}
		
		static public function makeLocalizedFieldName($fieldName, $language=null)
		{
			if(is_null($language))
			{
				$language = self::getLanguage();
			}
			return $fieldName.self::getColumnNameGlue().$language;
		}

		public function setOptions(Array $options)
	    {
	        foreach ($options as $key => $value) {
	            switch ($key) {
	                case self::LOCALIZATION:
	                    $this->setLocalization($value);
	                    break;
	             	case self::IDENTITY:
	                    $this->setIdentity($value);
	                    break;
	                default:
	                    parent::setOptions(array($key => $value));
	                    break;
	            }
	        }
	        return $this;
	    }

	    public function setLocalization($Localization)
	    {
	    	$this->_localization = $Localization;
	    	return $this;
	    }

	    public function getLocalization()
	    {
	    	return $this->_localization;
	    }

	    protected function setIdentity($Identity=Null)
		{
			if(is_int($Identity) && $Identity)
			{
				$this->_identity = $Identity;
			}
			return $this;
		}

		public function getDefaultValues($DefaultSource=null)
		{			$cols     = $this->_getCols();
	        $defaults = array_combine($cols, array_fill(0, count($cols), null));
	        if(!in_array($DefaultSource, array(self::DEFAULT_CLASS, self::DEFAULT_DB, self::DEFAULT_NONE)))
	        {
	            $DefaultSource = self::DEFAULT_NONE;
	        }
	        if($DefaultSource == self::DEFAULT_DB)
		    {
		        foreach ($this->_metadata as $metadataName => $metadata)
		        {
	                if (($metadata['DEFAULT'] != null) &&
	                    ($metadata['NULLABLE'] !== true || ($metadata['NULLABLE'] === true && isset($this->_defaultValues[$metadataName]) && $this->_defaultValues[$metadataName] === true)) &&
	                    (!(isset($this->_defaultValues[$metadataName]) && $this->_defaultValues[$metadataName] === false)))
	                {
	                    $defaults[$metadataName] = $metadata['DEFAULT'];
	                }
		        }
		  	}
	        return (array) $defaults;
		}
		
		public function getLocalizedFieldName($cleanFieldName)
		{
			if($this->getLocalization())
			{
				$languages = array($this->getLanguage(), $this->getBaseLanguage());
				$valueFlag = False;
				$cols = $this->getColumns();
				foreach($languages as $language)
				{
					$langColumnName = $this->makeLocalizedFieldName($cleanFieldName, $language);
					if(in_array($langColumnName, $cols))
					{
						return $langColumnName;
					}
				}			
			}
			require_once 'Zend/Db/Table/Exception.php';
			throw new Zend_Db_Table_Exception(sprintf('Specified column "%s" is not in table', $cleanFieldName));			
		}
		
		protected function initLocalizedFields()
		{
			$this->_localizedFields = array();
			$this->_localizedFieldsPrefixes = array();
			$this->_undefinedLocalizedFields = array();
			$fields = array_keys($this->getMetadata());
			
			$locFields = array();
			$undefinedLocFields = array();
			foreach($fields as $field)
			{
				if(preg_match("/^(.*)".$this->getColumnNameGlue().$this->getBaseLanguage()."$/s", $field, $matches))
				{
					$locFields[$matches[1]] = array();
				}
			}
			
			foreach($locFields as $field => $locs)
			{
				foreach($this->getLanguages() as $language)
				{
					$locFieldName = $this->makeLocalizedFieldName($field, $language);
					if(in_array($locFieldName, $fields))
					{
						$locFields[$field][$language] = $locFieldName;
						$this->_localizedFieldsPrefixes[$locFieldName] = $field;
					}
					else
					{
						if(!is_array($undefinedLocFields[$field]))
						{
							$undefinedLocFields[$field] = array();
						}
						$undefinedLocFields[$field][$language] = $locFieldName;
					}
				}
			}
			$this->_localizedFields = $locFields;
			$this->_undefinedLocalizedFields = $undefinedLocFields;
		}
		
		public function getUndefinedLocalizedFields()
		{
			if(is_null($this->_undefinedLocalizedFields) && $this->getLocalization())
			{
				$this->initLocalizedFields();
			}			
			return $this->_undefinedLocalizedFields;
		}
		
		public function getLocalizedFields()
		{
			if(is_null($this->_localizedFields) && $this->getLocalization())
			{
				$this->initLocalizedFields();
			}			
			return $this->_localizedFields;
		}
		
		public function getLocalizedFieldsPrefixes()
		{
			if(is_null($this->_localizedFieldsPrefixes) && $this->getLocalization())
			{
				$this->initLocalizedFields();
			}				
			return $this->_localizedFieldsPrefixes;
		}
		
		public function getLocalizedFieldPrefix($localizedField, $withLanguageCode = false)
		{
			$prefixes = $this->getLocalizedFieldsPrefixes();
			if(!isset($prefixes[$localizedField]))
			{
				require_once 'Zend/Db/Table/Exception.php';
				throw new Zend_Db_Table_Exception(sprintf('Specified column "%s" is not localized', $localizedField));			
			}
			if($withLanguageCode)
			{
				$locFields = $this->getLocalizedFields();
				return array($prefixes[$localizedField], array_search($localizedField, $locFields[$prefixes[$localizedField]]));
			}
			return $prefixes[$localizedField];
		}
	}
